<?php
include COMMON_PATH . '/Util/Qiniu/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Processing\PersistentFop;
const MIC_ADDONS_PATH = 'Addons/';
/**
 * [p 打印函数]
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function p($str){
	echo "<pre>";
	print_r($str);
	echo "</pre>";
}
/**
 * 删除目录及目录下所有文件或删除指定文件
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 */
function delDirAndFile($path, $delDir = FALSE) {
    $handle = opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function _encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? 'WZQXKJ' : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function _decrypt($data, $key = ''){
    $key    = md5(empty($key) ? 'WZQXKJ' : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
       $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}
/**
 * [GetRandStr 生成指定机数]
 * @param integer $len   [description]
 * @param array   $chars [description]
 */
function GetRandStr($len = 4, $chars = array()) {
    if (empty($chars)) {
        $chars = array( 
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",  
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",  
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",  
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",  
            "3", "4", "5", "6", "7", "8", "9" 
        );
    }
    
    $charsLen = count($chars) - 1; 
    shuffle($chars);   
    $output = ""; 
    for ($i=0; $i<$len; $i++) { 
        $output .= $chars[mt_rand(0, $charsLen)]; 
    }  
    return $output;  
}
/**
 * [friend_date 友好时间显示]
 * @param  [type] $time [时间戳]
 * @return [type]       [description]
 */
function friend_date($time){
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日 H:i', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}
/**
 * 根据大小返回标准单位 KB  MB GB等
 */
function get_size($size, $decimals = 2) {
    switch (true){
        case $size >= pow(1024, 3):
            return round($size / pow(1024, 3), $decimals) . " GB";
        case $size >= pow(1024, 2):
            return round($size / pow(1024, 2), $decimals) . " MB";
        case $size >= pow(1024, 1):
            return round($size / pow(1024, 1), $decimals) . " KB";
        default:
            return $size . 'B';
    }
}
/**
 * [object_array 数组对象转数组]
 * @param  [type] $array [数组对象]
 * @return [type]        [description]
 */
function object_array($array) {  
    if(is_object($array)) {  
        $array = (array)$array;  
     } if(is_array($array)) {  
         foreach($array as $key=>$value) {  
             $array[$key] = object_array($value);  
             }  
     }  
     return $array;  
}
/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}
/**
 * [GetQiniuToken 获取七牛TOKEN]
 * @param [type] $token_path [description]
 */
function GetQiniuToken($token_path = null){
    // 实例化七牛类
    $QiniuAuth = new Auth(C('QINIU_ACCESSKEY'), C('QINIU_SECRETKEY'));
    // 生成上传Token
    $token = $QiniuAuth->uploadToken(C('QINIU_BUCKET'));
    // 组装数据
    $token_config = array(
        'token'     => $token,
        'time'      => time() + 3600
    );
    // 写入Token
    file_put_contents($token_path, json_encode($token_config));
    return $token;
}
/**
 * [GetVideoInfo 获取单视频信息]
 * @param [type] $hash [description]
 * @param [type] $key  [description]
 * substr($ret['putTime'], 0, -7) 转换为时间戳而不是毫秒时间戳
 */
function GetVideoInfo($key = null){
    //初始化Auth状态
    $auth = new Auth(C('QINIU_ACCESSKEY'), C('QINIU_SECRETKEY'));
    //初始化BucketManager
    $bucketMgr = new BucketManager($auth);
    //获取文件的状态信息
    list($data, $err) = $bucketMgr->stat(C('QINIU_BUCKET'), $key);
    if ($err !== null) {
        p($err);
        return false;
    } else {
        return $data;
    }
}
/**
 * [CreateVideoImg 对视频进行截图]
 * @param [type] $key [description]
 */
function CreateVideoImg($key = null,$pipeline = 'player',$width = 480, $height = 400){
    // 获取授权凭证
    $auth = new Auth(C('QINIU_ACCESSKEY'), C('QINIU_SECRETKEY'));
    // 实例化类
    $pfop = new PersistentFop($auth, C('QINIU_BUCKET'), $pipeline);
    // 视频截图操作
    $fops = "vframe/jpg/offset/".mt_rand(1, 300)."/w/".$width."/h/".$height;
    // 执行截图操作
    list($id, $err) = $pfop->execute($key, $fops);
    if ($err != null) {
        return false;
    }
    // 获取截取状态
    list($data, $err) = $pfop->status($id);
    if ($err != null) {
        p($err);
        return false;
    } else {
        return array('id'=> isset($id) ? $id : $data['id']);
    }
}
/**
 * [QueryThumb 执行查询截图进度与状态]
 * @param [type] $key      [description]
 * @param string $pipeline [description]
 */
function QueryThumb($key, $pipeline = 'player'){
    // 获取授权凭证
    $auth = new Auth(C('QINIU_ACCESSKEY'), C('QINIU_SECRETKEY'));
    // 实例化类
    $pfop = new PersistentFop($auth, C('QINIU_BUCKET'), $pipeline);

    //查询截图的进度和状态
    list($ret, $err) = $pfop->status($key);
    if ($err != null) {
        p($err);
    } else {
        return $ret;
    }
}
/**
 * [CreateVideoAvthumb 对视频进行转码操作]
 * @param [type] $key      [description]
 * @param string $pipeline [description]
 */
function CreateVideoAvthumb($key = null, $pipeline = ''){
    $auth = new Auth(C('QINIU_ACCESSKEY'), C('QINIU_SECRETKEY'));
    $pfop = new PersistentFop($auth, C('QINIU_BUCKET'), $pipeline);
    // 标清、高清、超清
    $fops = array(
        'video_sd_id'       => 'avthumb/mp4/s/720x576/vcodec/libx264/vb/1.25m',
        'video_high_id'     => 'avthumb/mp4/s/1280x720/vcodec/libx264/vb/1.25m',
        'video_super_id'    => 'avthumb/mp4/s/1920x1080/vcodec/libx264/vb/1.25m'
    );
    // 批量转码
    foreach ($fops as $k => $v) {
        list($data[$k], $err[$k]) = $pfop->execute($key, $v);
    }
    return $data;
}
/**
 * [VideoKeyStatus 查询视频转码进度与状态]
 * @param string $id       [description]
 * @param string $pipeline [description]
 */
function VideoKeyStatus($id = '',$pipeline = ''){
    $auth = new Auth(C('QINIU_ACCESSKEY'), C('QINIU_SECRETKEY'));
    $pfop = new PersistentFop($auth, C('QINIU_BUCKET'), $pipeline);
    //查询转码的进度和状态
    list($data, $err) = $pfop->status($id);
    if ($err != null) {
        p($err);
        return false;
    } else {
        return $data;
    }
}
/**
 * [DelVideo 删除空间中的视频]
 * @param [type] $key [description]
 */
function DelVideo($key){
    //初始化Auth状态
    $auth = new Auth(C('QINIU_ACCESSKEY'), C('QINIU_SECRETKEY'));
    //初始化BucketManager
    $bucketMgr = new BucketManager($auth);

    //删除$bucket 中的文件 $key
    $err = $bucketMgr->delete(C('QINIU_BUCKET'), $key);
    if ($err !== null) {
        return false;
    } else {
        return true;
    }
}
/**
* 查询字符是否存在于某字符串
*
* @param $haystack 字符串
* @param $needle 要查找的字符
* @return bool
*/
function str_exists($haystack, $needle){
    return !(strpos($haystack, $needle) === FALSE);
}
/**
 * 数组进行整数映射转换
 * @param       $data
 * @param array $map
 */
function int_to_string(&$data, array $map = array('status' => array('0' => '禁止', '1' => '启用'))) {
    $map = (array)$map;
    foreach ($data as $n => $d)
    {
        foreach ($map as $name => $m)
        {
            if (isset($d[$name]) && isset($m[$d[$name]]))
            {
                $data[$n][$name . '_text'] = $m[$d[$name]];
            }
        }
    }
}
/**
* 对查询结果集进行排序
* @access public
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function list_sort_by($list,$field, $sortby = 'asc') {
   if(is_array($list)){
       $refer = $resultSet = array();
       foreach ($list as $i => $data)
           $refer[$i] = &$data[$field];
       switch ($sortby){
           case 'asc': // 正向排序
                asort($refer);
                break;
           case 'desc':// 逆向排序
                arsort($refer);
                break;
           case 'nat': // 自然排序
                natcasesort($refer);
                break;
       }
       foreach ( $refer as $key=> $val)
           $resultSet[] = &$list[$key];
       return $resultSet;
   }
   return false;
}
/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook,$params=array()){
    \Think\Hook::listen($hook,$params);
}

/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name){
    $class = "Addons\\{$name}\\{$name}Addon";
    return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
function get_addon_config($name){
    $class = get_addon_class($name);
    if(class_exists($class)) {
        $addon = new $class();
        return $addon->getConfig();
    }else {
        return array();
    }
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function addons_url($url, $param = array()){
    $url        = parse_url($url);
    $case       = C('URL_CASE_INSENSITIVE');
    $addons     = $case ? parse_name($url['scheme']) : $url['scheme'];
    $controller = $case ? parse_name($url['host']) : $url['host'];
    $action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

    /* 解析URL带的参数 */
    if(isset($url['query'])){
        parse_str($url['query'], $query);
        $param = array_merge($query, $param);
    }

    /* 基础参数 */
    $params = array(
        '_addons'     => $addons,
        '_controller' => $controller,
        '_action'     => $action,
    );
    $params = array_merge($params, $param); //添加额外参数

    return U('Addons/execute', $params);
}
/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ','){
    return explode($glue, $str);
}
/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ','){
    return implode($glue, $arr);
}
/**
 * [create_dir_or_files 基于数组创建目录和文件]
 * @param  [type] $files [description]
 * @return [type]        [description]
 */
function create_dir_or_files($files){
    foreach ($files as $key => $value) {
        if(substr($value, -1) == '/'){
            mkdir($value);
        }else{
            @file_put_contents($value, '');
        }
    }
}